package com.xiaoshuidi.cloud.module.member.service.comment;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.module.member.controller.admin.comment.vo.CommentDetail;
import com.xiaoshuidi.cloud.module.member.controller.admin.comment.vo.CommentPageVO;
import com.xiaoshuidi.cloud.module.member.controller.admin.comment.vo.CommentStatisticsReqVo;
import com.xiaoshuidi.cloud.module.member.controller.admin.comment.vo.CommentStatisticsVo;
import com.xiaoshuidi.cloud.module.member.controller.admin.comment.vo.CommentStewardPageReqVo;
import com.xiaoshuidi.cloud.module.member.controller.admin.comment.vo.CommentStewardPageVo;
import com.xiaoshuidi.cloud.module.member.controller.app.comment.vo.AppMemberListVO;
import com.xiaoshuidi.cloud.module.member.controller.app.comment.vo.MemberCommentCreateVO;
import com.xiaoshuidi.cloud.module.member.controller.app.comment.vo.MemberCommentRespVO;
import com.xiaoshuidi.cloud.module.member.enums.comment.CommentTypeEnum;
import com.xiaoshuidi.cloud.module.member.mapper.comment.MemberCommentMapper;
import com.xiaoshuidi.cloud.module.member.pojo.comment.MemberComment;
import com.xiaoshuidi.cloud.module.member.repository.MemberCommentRepository;
import com.xiaoshuidi.cloud.module.member.util.RoomHouseUtil;
import com.xiaoshuidi.cloud.module.member.util.TimeConvertUtils;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.RoomHouseApi;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomHouseRespVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MemberCommentServiceImpl extends ServiceImpl<MemberCommentMapper, MemberComment> implements MemberCommentService {
    private final MemberCommentRepository memberCommentRepository;

    private final RoomHouseApi roomHouseApi;

    @Override
    public Boolean create(MemberCommentCreateVO vo) {
        //根据消息id更新评论状态为已评价
        MemberComment memberComment = memberCommentRepository.getCommentByMessageId(vo.getMessageId());
        if (ObjectUtils.isNotEmpty(memberComment)) {
            //更新
            MemberComment m = new MemberComment();
            BeanUtils.copyProperties(vo, m);
            m.setId(memberComment.getId());
            m.setStatus(true);
            BigDecimal compositeScore = getCompositeScore(m);
            m.setCompositeScore(compositeScore);
            memberCommentRepository.updateById(m);
            return true;
        }
        memberCommentRepository.create(vo);
        return true;
    }

    public BigDecimal getCompositeScore(MemberComment comment) {
        //如果是新租
        if (comment.getCommentType().intValue() == CommentTypeEnum.SIGN.getType().intValue()) {
            //1.管家服务2.房屋环境3.物业环境:4.周边配套5入住满意度6线上运营
            BigDecimal compositeScore = (comment.getStewardScore().add(comment.getHouseScore()).add(comment.getPropertyEnvScore())
                    .add(comment.getAroundSupportScore()).add(comment.getCheckInFeelScore())
                    .add(comment.getOnlineScore())).divide(BigDecimal.valueOf(6), 2, BigDecimal.ROUND_HALF_UP);
            return compositeScore;
        } else if (comment.getCommentType().intValue() == CommentTypeEnum.RELET.getType().intValue()) {
            //续租评价 1.管家服务2.物业服务3.续租便捷度:4.整体满意度
            BigDecimal compositeScore = (comment.getStewardScore().add(comment.getPropertyScore())
                    .add(comment.getReletConvenienceScore()).add(comment.getOverallScore()))
                    .divide(BigDecimal.valueOf(5), 2, BigDecimal.ROUND_HALF_UP);
            return compositeScore;
        } else if (comment.getCommentType().intValue() == CommentTypeEnum.OUT.getType().intValue()) {
            //1.管家服务2.居住舒适度3.退租便捷度4二次入住推荐5品牌总体评价
            BigDecimal compositeScore = (comment.getStewardScore().add(comment.getLivingScore())
                    .add(comment.getRentOutConvenienceScore()).add(comment.getRecommendScore())
                    .add(comment.getBrandScore())).divide(BigDecimal.valueOf(5), 2, BigDecimal.ROUND_HALF_UP);
            return compositeScore;
        } else if (comment.getCommentType().intValue() == CommentTypeEnum.COMPANY_IN.getType().intValue()) {
            //1.管家服务2.房屋环境3物业环境4.周边配套5入住满意度
            BigDecimal compositeScore = (comment.getStewardScore().add(comment.getHouseScore())
                    .add(comment.getPropertyEnvScore()).add(comment.getAroundSupportScore())
                    .add(comment.getCheckInFeelScore())).divide(BigDecimal.valueOf(5), 2, BigDecimal.ROUND_HALF_UP);
            return compositeScore;
        } else if (comment.getCommentType().intValue() == CommentTypeEnum.COMPANY_OUT.getType().intValue()) {
            //1.管家服务2.居住舒适度3.迁出便捷度4二次入住推荐5品牌总体评价
            BigDecimal compositeScore = (comment.getStewardScore().add(comment.getLivingScore())
                    .add(comment.getRentOutConvenienceScore()).add(comment.getRecommendScore())
                    .add(comment.getBrandScore())).divide(BigDecimal.valueOf(5), 2, BigDecimal.ROUND_HALF_UP);
            return compositeScore;
        }
        return null;
    }

    @Override
    public MemberCommentRespVO getById(Long id) {
        return memberCommentRepository.getCommentById(id);
    }

    @Override
    public List<AppMemberListVO> getListByUserId(Long userId, Boolean status) {
        //1.查询此用户的所有评价信息
        List<MemberCommentRespVO> list = memberCommentRepository.getListByUserId(userId, status);
        //统计出各种情况的数量
        List<AppMemberListVO> result = new ArrayList<>();
        for (CommentTypeEnum value : CommentTypeEnum.values()) {
            AppMemberListVO vo = new AppMemberListVO();
            vo.setCommentType(value.getType());
            List<MemberCommentRespVO> collect = list.stream().filter(c -> c.getCommentType().intValue() == vo.getCommentType().intValue())
//                    .peek(c -> {
//                        MemberCommentRespVO commentRespVO = new MemberCommentRespVO();
//                        BeanUtils.copyProperties(c, commentRespVO);
//                        return commentRespVO;
//                    })
                    .collect(Collectors.toList());
            vo.setList(collect);
            result.add(vo);
        }
        return result;
    }

    @Override
    public List<CommentStatisticsVo> getCommentStatistics(CommentStatisticsReqVo reqVo) {
        reqVo.setBeginDateTime(TimeConvertUtils.startTimeConvert(reqVo.getBeginTime()));
        reqVo.setEndDateTime(TimeConvertUtils.endTimeConvert(reqVo.getEndTime()));
        //1.查询所有评价信息
        List<MemberComment> list = memberCommentRepository.getCommentStatistics(reqVo);
        List<CommentStatisticsVo> result = new ArrayList<>();
        for (CommentTypeEnum value : CommentTypeEnum.values()) {
            //查询相应评价枚举对应的评论
            CommentStatisticsVo vo = new CommentStatisticsVo();
            vo.setCommentType(value.getType());
            List<MemberComment> collect = list.stream().filter(c -> c.getCommentType().intValue() == vo.getCommentType().intValue()).collect(Collectors.toList());
            int size = collect.size();
            if (size > 0) {
                //管家服务
                BigDecimal stewardScore = collect.stream().map(MemberComment::getStewardScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //房屋环境
                BigDecimal houseScore = collect.stream().map(MemberComment::getHouseScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //物业环境
                BigDecimal propertyEnvScore = collect.stream().map(MemberComment::getPropertyEnvScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //周边配套
                BigDecimal aroundSupportScore = collect.stream().map(MemberComment::getAroundSupportScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //入住满意度
                BigDecimal checkInFeelScore = collect.stream().map(MemberComment::getCheckInFeelScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //线上运营
                BigDecimal onlineScore = collect.stream().map(MemberComment::getOnlineScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //综合评价分
                BigDecimal compositeScore = collect.stream().map(MemberComment::getCompositeScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //物业服务
                BigDecimal propertyScore = collect.stream().map(MemberComment::getPropertyScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //续租便捷度
                BigDecimal reletConvenienceScore = collect.stream().map(MemberComment::getReletConvenienceScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //整体满意度
                BigDecimal overallScore = collect.stream().map(MemberComment::getOverallScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //居住舒适度
                BigDecimal livingScore = collect.stream().map(MemberComment::getLivingScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //退租/迁出便捷度
                BigDecimal rentOutConvenienceScore = collect.stream().map(MemberComment::getRentOutConvenienceScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //二次入住与推荐
                BigDecimal recommendScore = collect.stream().map(MemberComment::getRecommendScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                //品牌总体评价
                BigDecimal brandScore = collect.stream().map(MemberComment::getBrandScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(size), 2, BigDecimal.ROUND_HALF_UP);
                CommentDetail commentDetail = new CommentDetail();
                commentDetail.setStewardScore(stewardScore);
                commentDetail.setHouseScore(houseScore);
                commentDetail.setPropertyEnvScore(propertyEnvScore);
                commentDetail.setAroundSupportScore(aroundSupportScore);
                commentDetail.setCheckInFeelScore(checkInFeelScore);
                commentDetail.setOnlineScore(onlineScore);
                commentDetail.setCompositeScore(compositeScore);
                commentDetail.setPropertyScore(propertyScore);
                commentDetail.setReletConvenienceScore(reletConvenienceScore);
                commentDetail.setOverallScore(overallScore);
                commentDetail.setLivingScore(livingScore);
                commentDetail.setRentOutConvenienceScore(rentOutConvenienceScore);
                commentDetail.setRecommendScore(recommendScore);
                commentDetail.setBrandScore(brandScore);
                commentDetail.setCommentNum(size);
                vo.setData(commentDetail);
            }

            result.add(vo);
        }
        return result;
    }

    @Override
    public PageResult<MemberCommentRespVO> getCommentPage(CommentPageVO pageVO) {
        //
        pageVO.setBeginDateTime(TimeConvertUtils.startTimeConvert(pageVO.getBeginTime()));
        pageVO.setEndDateTime(TimeConvertUtils.endTimeConvert(pageVO.getEndTime()));
        IPage<MemberCommentRespVO> page = memberCommentRepository.getCommentPage(pageVO);
        List<MemberCommentRespVO> records = page.getRecords();
        // 调用接口查询房源具体位置
        records = records.stream().peek(r -> {
            if (r.getRoomId() != null) {
                try {

                    CommonResult<RoomHouseRespVo> houseinfoById = roomHouseApi.getRoomHouseinfoById(r.getRoomId());
                    log.info("房源id为:{},########################$$$$$$$$$$$$,房源信息为111111111111{}", r.getRoomId(), JsonUtils.toJsonString(houseinfoById));
                    if (houseinfoById.isSuccess()) {
                        if (houseinfoById.getData() != null) {
                            r.setRoomHouse(RoomHouseUtil.getHouseFullName(houseinfoById.getData()));
                        }
                    }
                } catch (Exception e) {
                    log.error("调取房源获取房源信息异常,roomId:" + r.getRoomId());
                }
            }
        }).collect(Collectors.toList());

        PageResult<MemberCommentRespVO> result = PageResult.empty();
        result.setTotal(page.getTotal());
        result.setList(records);
        return result;
    }

    @Override
    public PageResult<CommentStewardPageVo> getCommentStewardPage(CommentStewardPageReqVo pageVO) {
        IPage<CommentStewardPageVo> page = memberCommentRepository.getCommentStewardPage(pageVO);
        PageResult<CommentStewardPageVo> result = PageResult.empty();
        result.setTotal(page.getTotal());
        result.setList(page.getRecords());
        return result;
    }

    @Override
    public MemberCommentRespVO getByMessageId(Long id) {
        return memberCommentRepository.getByMessageId(id);
    }

    @Override
    public void updateUserId(Long oldUserId, Long userId) {
        this.baseMapper.updateUserId(oldUserId,userId);
    }
}
